package com.wei.controller.web;

import com.wei.blog.common.dto.BlogPage;
import com.wei.blog.common.exception.BlogException;
import com.wei.blog.common.help.UserHelp;
import com.wei.blog.common.utils.R;
import com.wei.entity.InvitationEntity;
import com.wei.entity.UserEntity;
import com.wei.service.CommentService;
import com.wei.service.ILikeService;
import com.wei.service.InvitationService;
import com.wei.service.UserService;
import com.wei.vo.CommentVo;
import com.wei.vo.LikeVo;
import com.wei.vo.UserToken;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.listener.Topic;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import java.util.Date;

@Controller
@RequestMapping("/topic")
public class TopicController {
    @Autowired
    private UserHelp userHelp;
    @Autowired
    private InvitationService invitationService;
    @Autowired
    private UserService userService;
    @Autowired
    private CommentService commentService;
    @Autowired
    private ILikeService likeService;

    //新增接口
    @PostMapping("/publish")
    @ResponseBody
    R publish(@RequestBody InvitationEntity invitationEntity) {
        //获取用户信息 从redis获取
        UserToken userToken = userHelp.get();
        if (userToken == null) {
            throw new BlogException("用户没有登录");
        }
        invitationEntity.setStatus(1);
        invitationEntity.setCreateTime(new Date());
        invitationEntity.setUid(userToken.getUid());
        //使用mybatis-pius
        invitationService.save(invitationEntity);
        return R.ok();

    }

    @GetMapping("/detail/{id}")
    String detail(BlogPage<CommentVo> page,
                  @PathVariable Integer id,
                  ModelMap map
    ) {
        //查看帖子信息
        InvitationEntity topic = invitationService.getById(id);
        //查看帖子作者信息
        UserEntity user = userService.getById(topic.getUid());
        //设置帖子数据
        page.setSize(5);
        //帖子评论
        page = commentService.getCommentListByTid(page, id);
        //帖子点赞
        LikeVo likeVo = new LikeVo();
        likeVo.setEntityType(1);
        likeVo.setEntityId(id);
        if (userHelp.get()!=null){
            likeVo.setUserId(userHelp.get().getUid());
        }
        //查帖子的点赞数量
        Long likeCount = likeService.likeCount(likeVo);
        //当前用户对该帖子的点赞状态
        boolean likeStatus = likeService.likeStatus(likeVo);

        //设置page路径
        page.setPath("/topic/detail"+id);
        //把查到的数据放在modelMap中
        map.addAttribute("topic",topic);
        map.addAttribute("user",user);
        map.addAttribute("page",page);
        map.addAttribute("likeCount",likeCount);
        map.addAttribute("likeStatus",likeStatus?1:0);
        return "site/discuss-detail";
    }

}
